package cn.gtv.sdk.dcas.api;

import android.content.Context;

import androidx.lifecycle.Observer;

import com.sad.jetpack.v1.datamodel.api.IDataModelObtainedCallback;
import com.sad.jetpack.v1.datamodel.api.IDataModelResponse;
import com.sad.jetpack.v1.datamodel.api.utils.LogcatUtils;

import java.util.List;

import cn.gtv.sdk.dcas.api.db.Event;

public class DefaultEventDataDBObserver implements Observer<List<Event>> {

    private IDCASRecorderStrategy uploadStrategy;
    private Context context;
    public DefaultEventDataDBObserver(Context context, IDCASRecorderStrategy uploadStrategy){
        this.context=context;
        this.uploadStrategy=uploadStrategy;
    }
    @Override
    public void onChanged(List<Event> events) {
        LogcatUtils.e("----------->DCAS日志库变化："+events.size());
        if (events.size()>0 && uploadStrategy==null){
            doUpload(context,events);
        }
        else {
            if (events.size()>0 && uploadStrategy.enableUpload(events)){
                doUpload(context,events);
            }
        }

    }

    private void doUpload(Context context,List<Event> events){
        LogcatUtils.e("----------->DCAS开始上报："+events.size());
        if (DCASCore.isUploading(context)){
            LogcatUtils.e("----------->DCAS上报中止：已经在上报了");
            return;
        }
        //立即删除数据已经消费完的数据，防止重复消费
        EventsManager.getInstance(context).deleteOldest(events.get(events.size() - 1).getUpdateTime());
        if(DCASCore.globalConfig.getServerTokenFactory()!=null){
            DCASCore.globalConfig.getServerTokenFactory().onCreateServerToken(new IServerTokenConsumer() {
                @Override
                public void optServerToken(String serverToken) {
                    DCASDataUploaderImpl.newBuilder(context)
                            .tag("track_data_upload")
                            .callback(new IDataModelObtainedCallback() {
                                @Override
                                public void onDataObtainedCompleted(IDataModelResponse response) {
                                    //上传完毕
                                }
                            })
                            .build()
                            .postDCASDataToServer(events);
                }
            });
        }
    }
}
